package org.example;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

public class test14 {
    public static void main(String[] args) {
        try {
            // 创建对象
            ObjectMapper om = new ObjectMapper();

            // 创建sdf对象并设置日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            // 创建自定义对象
            LocalDateTime dateTime = LocalDateTime.now();
            MyObject mo = new MyObject();
            om.registerModule(new JavaTimeModule());
            mo.setDateTime(dateTime);
            // 将对象序列化之后转换为JSON字符串
            String json = om.writeValueAsString(mo);
            System.out.println("序列化得到的json: " + json);

            // 将 JSON 字符串反序列化为对象
            MyObject om1 = om.readValue(json, MyObject.class);
            System.out.println("反序列化得到的对象: " + om1);

            System.out.println("---------");

            //方法二使用JavaTimeModule模块来完成
            ObjectMapper objectMapper = new ObjectMapper();

            //注册模块
            objectMapper.registerModule(new JavaTimeModule());

            //使用模块进行序列化
            MyObject myObject = new MyObject();
            myObject.setDateTime(dateTime);

            // 将对象序列化之后转换为JSON字符串
            String json1 = objectMapper.writeValueAsString(myObject);
            System.out.println("序列化得到的json: " + json1);

            // JSON字符串反序列化为对象
            MyObject json2 = objectMapper.readValue(json, MyObject.class);
            System.out.println("反序列化得到的对象: " + json2);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class MyObject {
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime dateTime;

        //需要get set一起定义
        public void setDateTime(LocalDateTime dateTime) {
            this.dateTime = dateTime;
        }

        @Override
        public String toString() {
            return "{" +
                    "date=" + dateTime +
                    '}';
        }

    }
}




